package nancal.mp.db.mysql.extend

import nancal.mp.db.mysql.dbr
import nancal.mp.db.mysql.table.AdminGroup
import nbcp.base.comm.ApiResult
import nbcp.base.db.LoginUserModel
import nbcp.base.extend.AsString
import nbcp.base.extend.minus
import nbcp.base.utils.CodeUtil
import nbcp.base.utils.Md5Util
import nbcp.myoql.db.sql.query
import nbcp.myoql.db.sql.update
import java.time.LocalDateTime

/**
 * 登录验证，返回错误消息
 */

fun AdminGroup.admin_user_table.doLogin(
    loginName: String,
    password: String,
    requestToken: String,
):
        ApiResult<LoginUserModel> {

    var loginUser = dbr.admin.admin_login_user.query()
        .where { it.loginName sqlEquals  loginName }
        .toEntity();

    if (loginUser == null) {
        return ApiResult.error("找不到用户：" + loginName);
    }

    if (loginUser.errorLoginTimes > 10 && (LocalDateTime.now() - loginUser.lastLoginAt).toMinutes() < 5) {
        return ApiResult.error("帐户频繁登录失败，已被锁定5分钟！")
    }

    var user = dbr.admin.admin_user.query()
        .where { it.loginName sqlEquals loginName }
        .toEntity()

    if (user == null) {
        return ApiResult.error("找不到用户：" + loginName)
    }

    if (loginUser.password != Md5Util.getBase64Md5(password)) {

        dbr.admin.admin_login_user.update()
            .set { it.lastLoginAt to LocalDateTime.now() }
            .set { it.errorLoginTimes to (loginUser.errorLoginTimes + 1) }
            .where { it.loginName sqlEquals loginName }
            .exec();
        return ApiResult.error("密码错误")
    }

    var token = requestToken.AsString(CodeUtil.getCode())
    dbr.admin.admin_login_user.update()
        .set { it.lastLoginAt to LocalDateTime.now() }
        .set { it.errorLoginTimes to 0 }
        .where { it.loginName sqlEquals loginName }
        .exec();


    return ApiResult.of(
        LoginUserModel().apply {
            this.system = "corp"
            this.id = user.id
            this.loginName = user.loginName
            this.isAdmin = user.isAdmin
            this.name = user.name
            this.token = token
            this.loginField = "loginName"
        }
    )
}
